﻿#region [ Usings ]

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using SP = Microsoft.SharePoint.WebPartPages;

#endregion

namespace BPC.SharePoint2010.AtoZWebPart.ToolParts
{
    /// <summary>
    /// Shows additional WebPart Property settings 
    /// </summary>
    public class AtoZToolPart : ToolPart
    {
        #region [ Constants ] 

        private const int TEXTBOX_COLUMNS = 30;
        private const int TEXTBOX_ROWS = 20;

        private string TOOLPART_NAME = "Enhanced Settings";

        private string FIELD_LABEL_VIEW_NAME_FIELDS = "Views";
        private string FIELD_DESCRIPTION_VIEW_NAME_FIELDS = "List of available Views";

        private string FIELD_LABEL_FIELDS_FIELDS = "Fields";
        private string FIELD_DESCRIPTION_FIELDS_FIELDS = "List of available fields";

        private string TEXTBOX_CSS = "UserInput";

        #endregion

        #region [ Constructors ]

        public AtoZToolPart()
        {
            this.Title = TOOLPART_NAME;            
        }

        #endregion

        #region [ Fields ]

        #region [ Controls ]

        AtoZWebPart.AtoZWebPart _webpart;
        
        DropDownList _viewsDDL;
        DropDownList _fieldsDDL;

        protected Table _containerTable;

        #endregion

        #endregion

        #region [ Overrides ]

        /// <summary>
        /// Adds the aditional table to menu 
        /// </summary>
        protected override void CreateChildControls()
        {
            _webpart = this.WebPartToEdit as AtoZWebPart.AtoZWebPart;

            Table containerTable = new Table();            
            containerTable.Rows.Add(GetViewsRow());
            containerTable.Rows.Add(GetFieldsRow()); 
            this.Controls.Add(containerTable);

            base.CreateChildControls();
        }

        protected override void OnLoad(System.EventArgs e)
        {
            EnsureChildControls();
            if(_viewsDDL.Items.Count <1)
            {
                List<SP.XsltListViewWebPart> _listviews;

                _listviews = GetListViewsWebPart();
                foreach (SP.XsltListViewWebPart listView in _listviews)
                {
                    ListItem listItem = new ListItem(listView.Title, listView.Title);
                    _viewsDDL.Items.Add(listItem);                    
                }

                //set values
                if (!string.IsNullOrEmpty(this._webpart.ViewName))
                {
                    _viewsDDL.SelectedValue = this._webpart.ViewName;

                }
                SetFieldsForView(_viewsDDL.SelectedItem.Text);
                if (!string.IsNullOrEmpty(this._webpart.FieldName))
                {
                    _fieldsDDL.SelectedValue = this._webpart.FieldName;
                }
            }
            
            base.OnLoad(e);
        }
                
        /// <summary>
        /// Apply the changes to the webpart properties
        /// </summary>
        public override void ApplyChanges()
        {           
            try
            {
                _webpart.ViewName = _viewsDDL.SelectedItem.Text;
            }
            catch { }

            try
            {
                _webpart.FieldName = _fieldsDDL.SelectedItem.Text;
            }
            catch { }           
            

            base.ApplyChanges();
        }

        protected override void RenderToolPart(HtmlTextWriter output)
        {
            base.RenderToolPart(output);
        }

        #endregion

        #region [ Protected ]

        protected List<SP.XsltListViewWebPart> GetListViewsWebPart()
        {
            List<SP.XsltListViewWebPart> listviews = new List<SP.XsltListViewWebPart>();
            foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in this.WebPartManager.WebParts)
            {
                if (webPart is SP.XsltListViewWebPart)
                {
                    listviews.Add(webPart as SP.XsltListViewWebPart);                    
                }
            }
            return listviews;
        }      

        #endregion

        #region [ Private Methods ]

        #region ToolPanel building functions

        private TableRow GetViewsRow()
        {
            TableRow row = new TableRow();
            TableCell cell = new TableCell();

            _viewsDDL = new DropDownList();
            _viewsDDL.AutoPostBack = true;

            _viewsDDL.SelectedIndexChanged += new System.EventHandler(ViewsDDL_SelectedIndexChanged);

            _viewsDDL.CssClass = TEXTBOX_CSS;

            cell.Controls.Add(getFieldLabel(FIELD_LABEL_VIEW_NAME_FIELDS, _viewsDDL.ClientID, FIELD_DESCRIPTION_VIEW_NAME_FIELDS));
            cell.Controls.Add(new LiteralControl("<div class=\"UserSectionBody\"><div class=\"UserControlGroup\"><nobr>"));

            cell.Controls.Add(_viewsDDL);
            cell.Controls.Add(new LiteralControl("</nobr></div></div>"));

            row.Cells.Add(cell);

            return row;
        }

        private TableRow GetFieldsRow()
        {
            TableRow row = new TableRow();
            TableCell cell = new TableCell();

            _fieldsDDL = new DropDownList();
            _fieldsDDL.CssClass = TEXTBOX_CSS;

            cell.Controls.Add(getFieldLabel(FIELD_LABEL_FIELDS_FIELDS, _fieldsDDL.ClientID, FIELD_DESCRIPTION_FIELDS_FIELDS));
            cell.Controls.Add(new LiteralControl("<div class=\"UserSectionBody\"><div class=\"UserControlGroup\"><nobr>"));

            cell.Controls.Add(_fieldsDDL);
            cell.Controls.Add(new LiteralControl("</nobr></div></div>"));

            row.Cells.Add(cell);

            return row;
        }


        /// <summary>
        /// Renders out field label
        /// </summary>
        /// <param name="labelText"></param>
        /// <param name="controlid"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        private LiteralControl getFieldLabel(string labelText, string controlid, string description)
        {

            string html = string.Format("<div class=\"UserSectionHead\"><label title='{0}' for='{1}'>{2}:</label></div>", HttpUtility.HtmlAttributeEncode(description), controlid, labelText);

            LiteralControl literal = new LiteralControl(html);
            return literal;
        }

        #endregion

        private void SetFieldsForView(string viewTitle)
        {
            List<SP.XsltListViewWebPart> _listviews;

            _listviews = GetListViewsWebPart();
            if (_listviews != null)
            {
                foreach (SP.XsltListViewWebPart listView in _listviews)
                {
                    if (listView.Title.Equals(viewTitle))
                    {
                        SPList list = SPContext.Current.Web.Lists[listView.ListId];
                        SPView view = list.Views[new Guid(listView.ViewGuid)];
                        _fieldsDDL.DataSource = view.ViewFields;
                        _fieldsDDL.DataBind();
                        break;
                    }
                }
            }
        }

        private void ViewsDDL_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            SetFieldsForView(_viewsDDL.SelectedItem.Text);
        }

        #endregion
    }
}
